package cn.wolfcode.luowowo.job;


import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.enum1.RedisKeys;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.vo.StatisVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisDataPersistenceJob {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Scheduled(cron="0/10 * * * * ?")
    public void RedisToMongo(){
        //从redis中拿到vo对象,将其设置给mongodb中的攻略明细对象中
        //获取所有攻略明细对象
        List<Strategy> list = strategyService.list();
        for (Strategy strategy : list) {
            //获取key
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.id);
            //判断redis中是否有值
            if(template.hasKey(key)){
                String s = template.opsForValue().get(key);
                StatisVo statisVo = JSON.parseObject(s, StatisVo.class);
                BeanUtils.copyProperties(statisVo,strategy);
                strategyService.update(strategy);
            }
        }
        //从redis中拿到用户的收藏列表
        //获取所有用户
        List<UserInfo> users = userInfoService.list();
        for (UserInfo user : users) {
            //获取key
            String key = RedisKeys.STRATEGY_FAVORNUM.join(user.getId());
           //从redis中拿
            String s = redisTemplate.opsForValue().get(key);
            List sids = JSON.parseArray(s);
            //设置进用户中
            user.setStraygys(sids);
            //更新
            userInfoService.update(user);
        }
    }
}
